//
//  ZBLivePlanViewController.m
//  ZhiBo
//
//  Created by huangtie on 2017/11/8.
//  Copyright © 2017年 huangtie. All rights reserved.
//

#import "ZBLivePlanViewController.h"
#import "ZBLiveViewController.h"
#import "ZBLiveChannel.h"
#import "ZBLiveClassPicker.h"
#import "SMNavigationController.h"
#import "ZBAppDelegate.h"

#define LEFT_SPACE 70

@interface ZBLivePlanViewController ()<UITableViewDelegate,UITableViewDataSource,ZBLiveClassPickerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, UITextFieldDelegate>

@property (nonatomic , strong) UIImageView *backImageView;

@property (nonatomic , strong) UIButton *quitBtn;

@property (nonatomic , strong) UITableView *tableView;

@property (nonatomic , strong) NSArray <UITableViewCell *> *cells;

@property (nonatomic , strong) UITableViewCell *themeCell;
@property (nonatomic , strong) UITextField *themeTextField;

@property (nonatomic , strong) UITableViewCell *tagCell;
@property (nonatomic , strong) UIButton *tagBtn;
@property (nonatomic , strong) UILabel *tagLabel;

@property (nonatomic , strong) UITableViewCell *picCell;
@property (nonatomic , strong) UIButton *picBtn;
@property (nonatomic , strong) UIImageView *liveImageView;

@property (nonatomic , strong) UITableViewCell *orientationCell;
@property (nonatomic , strong) UIButton *verticalBtn;
@property (nonatomic , strong) UIButton *horizontalBtn;

@property (nonatomic , strong) NSArray <ZBLiveClass *> *liveClassList;
@property (nonatomic , strong) ZBLiveClass *liveClass;
@property (nonatomic , strong) ZBLiveClassPicker *classPicker;

@property (nonatomic , strong) NSData *imageData;

@end

@implementation ZBLivePlanViewController

- (BOOL)shouldAutorotate
{
    return NO;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.backImageView = [[UIImageView alloc] init];
    self.backImageView.image = [UIImage imageNamed:@"logo"];
    [self.backImageView sizeToFit];
    self.backImageView.centerX = self.view.width / 2;
    self.backImageView.top = FLEXIBLE_WIDTH_55INCH(200);
    [self.view addSubview:self.backImageView];
    
    UIView *mask = [[UIView alloc] initWithFrame:self.view.bounds];
    mask.backgroundColor = UICOLOR_RGB(0, 0, 0, .52);
    [self.view addSubview:mask];
    
    self.quitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.quitBtn.size = CGSizeMake(40, 40);
    [self.quitBtn setImage:[UIImage imageNamed:@"cancel"] forState:UIControlStateNormal];
    [self.quitBtn addTarget:self action:@selector(quitClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.cells = @[self.themeCell , self.tagCell , self.picCell , self.orientationCell];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = [self headerView];
    self.tableView.tableFooterView = [self footerView];
    [self.view addSubview:self.tableView];
    
    [self requestCatList];
    
    self.classPicker = [[ZBLiveClassPicker alloc] init];
    self.classPicker.delegate = self;
    [self.view addSubview:self.classPicker];
}

#pragma mark GET_SET
- (UIView *)headerView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, FLEXIBLE_WIDTH_55INCH(110))];
    view.backgroundColor = [UIColor clearColor];
    self.quitBtn.right = view.width - 20;
    self.quitBtn.top = 30;
    [view addSubview:self.quitBtn];
    return view;
}

- (UIView *)footerView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 95)];
    view.backgroundColor = [UIColor clearColor];
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.size = CGSizeMake(view.width - 100, view.height - 50);
    loginBtn.centerX = view.width / 2;
    loginBtn.centerY = view.height / 2;
    loginBtn.backgroundColor = UICOLOR_ARGB(0xfffb3e3f);
    [loginBtn setTitle:@"开始直播" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = FONT_NORMAL_14;
    loginBtn.layer.cornerRadius = loginBtn.height / 2;
    loginBtn.clipsToBounds = YES;
    [loginBtn addTarget:self action:@selector(beginLiveClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:loginBtn];

    return view;
}

- (UITableViewCell *)themeCell{
    if (!_themeCell) {
        _themeCell = [[UITableViewCell alloc] init];
        _themeCell.backgroundColor = [UIColor clearColor];
        _themeCell.contentView.backgroundColor = [UIColor clearColor];
        _themeCell.size = CGSizeMake(SCREEN_WIDTH, 110);
        _themeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILabel *title = [[UILabel alloc] init];
        title.font = FONT_NORMAL_18;
        title.textColor = UICOLOR_ARGB(0xffffffff);
        title.text = @"给直播写个主题吧!";
        [title sizeToFit];
        title.top = 25;
        title.centerX = _themeCell.width / 2;
        [_themeCell addSubview:title];
        
        self.themeTextField = [[UITextField alloc] init];
        self.themeTextField.width = FLEXIBLE_WIDTH_55INCH(160);
        self.themeTextField.height = 35;
        self.themeTextField.top = title.bottom + 10;
        self.themeTextField.font = FONT_NORMAL_18;
        self.themeTextField.textColor = UICOLOR_ARGB(0xffffffff);
        [self.themeTextField setValue:UICOLOR_ARGB(0xffd2d2d2) forKeyPath:@"_placeholderLabel.textColor"];
        self.themeTextField.centerX = _themeCell.width / 2;
        self.themeTextField.textAlignment = NSTextAlignmentCenter;
        self.themeTextField.returnKeyType = UIReturnKeyDone;
        self.themeTextField.delegate = self;
        [_themeCell addSubview:self.themeTextField];
        
        CAShapeLayer *border = [CAShapeLayer layer];
        //线的颜色
        border.strokeColor = UICOLOR_ARGB(0xffffffff).CGColor;
        //填充的颜色
        border.fillColor = [UIColor clearColor].CGColor;
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(0, self.themeTextField.height)];
        [path addLineToPoint:CGPointMake(self.themeTextField.width, self.themeTextField.height)];
        //设置路径
        border.path = path.CGPath;
        //线的宽度
        border.lineWidth = 1.f;
        [self.themeTextField.layer addSublayer:border];
    }
    return _themeCell;
}

- (UITableViewCell *)tagCell
{
    if (!_tagCell) {
        _tagCell = [[UITableViewCell alloc] init];
        _tagCell.backgroundColor = [UIColor clearColor];
        _tagCell.contentView.backgroundColor = [UIColor clearColor];
        _tagCell.selectionStyle = UITableViewCellSelectionStyleNone;
        _tagCell.size = CGSizeMake(SCREEN_WIDTH, 40);
        
        self.tagBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.tagBtn setTitleColor:UICOLOR_ARGB(0xffffffff) forState:UIControlStateNormal];
        [self.tagBtn setTitle:@"#选择话题标签" forState:UIControlStateNormal];
        self.tagBtn.titleLabel.font = FONT_NORMAL_14;
        [self.tagBtn addTarget:self action:@selector(tagClick) forControlEvents:UIControlEventTouchUpInside];
        [self.tagBtn sizeToFit];
        self.tagBtn.height = _tagCell.height;
        self.tagBtn.left = self.themeTextField.left;
        self.tagBtn.centerY = _tagCell.height / 2;
        [_tagCell addSubview:self.tagBtn];
    }
    return _tagCell;
}

- (UITableViewCell *)picCell
{
    if (!_picCell) {
        _picCell = [[UITableViewCell alloc] init];
        _picCell.backgroundColor = [UIColor clearColor];
        _picCell.contentView.backgroundColor = [UIColor clearColor];
        _picCell.size = CGSizeMake(SCREEN_WIDTH, FLEXIBLE_WIDTH_55INCH(108) + 20);
        _picCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.picBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.picBtn.size = CGSizeMake(FLEXIBLE_WIDTH_55INCH(160), _picCell.height - 20);
        [self.picBtn setTitleColor:UICOLOR_ARGB(0xffffffff) forState:UIControlStateNormal];
        [self.picBtn setTitle:@"+ 封面图片" forState:UIControlStateNormal];
        [self.picBtn addTarget:self action:@selector(pictureClick) forControlEvents:UIControlEventTouchUpInside];
        self.picBtn.titleLabel.font = FONT_NORMAL_16;
        self.picBtn.centerX = _picCell.width / 2;
        self.picBtn.centerY = _picCell.height / 2;
        self.picBtn.clipsToBounds = YES;
        
        self.liveImageView = [[UIImageView alloc] init];
        self.liveImageView.frame = self.picBtn.frame;
        self.liveImageView.clipsToBounds = YES;
        self.liveImageView.contentMode = UIViewContentModeScaleAspectFit;
        
        [_picCell addSubview:self.liveImageView];
        [_picCell addSubview:self.picBtn];
        
        CAShapeLayer *border = [CAShapeLayer layer];
        //虚线的颜色
        border.strokeColor = UICOLOR_ARGB(0xffffffff).CGColor;
        //填充的颜色
        border.fillColor = [UIColor clearColor].CGColor;
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.picBtn.bounds cornerRadius:0];
        //设置路径
        border.path = path.CGPath;
        border.frame = self.picBtn.bounds;
        //虚线的宽度
        border.lineWidth = 1.f;
        //虚线的间隔
        border.lineDashPattern = @[@4, @2];
        [self.picBtn.layer addSublayer:border];
    }
    return _picCell;
}

- (UITableViewCell *)orientationCell
{
    if (!_orientationCell) {
        _orientationCell = [[UITableViewCell alloc] init];
        _orientationCell.backgroundColor = [UIColor clearColor];
        _orientationCell.contentView.backgroundColor = [UIColor clearColor];
        _orientationCell.size = CGSizeMake(SCREEN_WIDTH, 42 + 10);
        _orientationCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.verticalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.verticalBtn.size = CGSizeMake(80, _orientationCell.height - 10);
        [self.verticalBtn setImage:[UIImage imageNamed:@"live_rect"] forState:UIControlStateNormal];
        [self.verticalBtn setImage:[UIImage imageNamed:@"live_rect_s"] forState:UIControlStateSelected];
        [self.verticalBtn setTitle:@"横屏" forState:UIControlStateNormal];
        [self.verticalBtn setTintColor:UICOLOR_ARGB(0xffffffff)];
        self.verticalBtn.titleLabel.font = FONT_NORMAL_14;
        self.verticalBtn.left = self.themeTextField.left;
        self.verticalBtn.centerY = _orientationCell.height / 2;
        self.verticalBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 35);
        self.verticalBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 25);
        self.verticalBtn.selected = YES;
        [self.verticalBtn addTarget:self action:@selector(orientationClick:) forControlEvents:UIControlEventTouchUpInside];
        [_orientationCell addSubview:self.verticalBtn];
        
        self.horizontalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.horizontalBtn.size = CGSizeMake(80, _orientationCell.height - 10);
        [self.horizontalBtn setImage:[UIImage imageNamed:@"live_rect"] forState:UIControlStateNormal];
        [self.horizontalBtn setImage:[UIImage imageNamed:@"live_rect_s"] forState:UIControlStateSelected];
        [self.horizontalBtn setTitle:@"竖屏" forState:UIControlStateNormal];
        [self.horizontalBtn setTintColor:UICOLOR_ARGB(0xffffffff)];
        self.horizontalBtn.titleLabel.font = FONT_NORMAL_14;
        self.horizontalBtn.left = self.verticalBtn.right;
        self.horizontalBtn.centerY = _orientationCell.height / 2;
        self.horizontalBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 35);
        self.horizontalBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 25);
        [self.horizontalBtn addTarget:self action:@selector(orientationClick:) forControlEvents:UIControlEventTouchUpInside];
        [_orientationCell addSubview:self.horizontalBtn];
    }
    return _orientationCell;
}

#pragma mark Action
- (void)tagClick
{
    [self.view endEditing:YES];
    [self.classPicker display:self.liveClassList];
}

- (void)pictureClick
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"设置封面" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍一张" otherButtonTitles:@"从相册获取", nil];
    [sheet showInView:self.view];
}

- (void)quitClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)beginLiveClick
{
    [self.view endEditing:YES];
    if (!self.themeTextField.text.length) {
        [self.view makeToast:@"请输入直播主题!"];
        [self.themeTextField becomeFirstResponder];
        return;
    }
    
    if (self.themeTextField.text.length > 20) {
        [self.view makeToast:@"最多只能输入20个字符!"];
        [self.themeTextField becomeFirstResponder];
        return;
    }
    
    if (!self.liveClass) {
        [self.view makeToast:@"请选择话题标签!"];
        return;
    }
    
    if (!self.imageData) {
        [self.view makeToast:@"请选择直播封面!"];
        return;
    }
    [self requestStartLive];
}

- (void)orientationClick:(UIButton *)button
{
    self.verticalBtn.selected = NO;
    self.horizontalBtn.selected = NO;
    button.selected = YES;
}

#pragma mark Request
- (void)requestCatList
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WS(weakSelf)
    [SMNetwork requestOnPOST:SM_Url_GetCatalogue param:@{} completion:^(NSURLSessionDataTask * _Nullable task, id  _Nullable result, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (!error) {
            if ([[result objectForKey:@"code"] integerValue] == 200) {
                
                NSArray *data = [result objectForKey:@"data"];
                NSMutableArray *array = [NSMutableArray array];
                for (NSDictionary *dict in data) {
                    ZBLiveClass *class = [ZBLiveClass mj_objectWithKeyValues:dict];
                    [array addObject:class];
                }
                weakSelf.liveClassList = array;
            }else{
                [weakSelf.view makeToast:[result objectForKey:@"msg"]];
            }
        }else{
            [weakSelf.view makeToast:TIP_LOAD_FAILED];
        }
    }];
}

- (void)requestStartLive
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WS(weakSelf)
    NSDictionary *param = @{@"token":[SMUserManager shareManager].token, @"cat_id" : self.liveClass.cat_id, @"topic" : self.themeTextField.text};
    [SMNetwork requestOnUpload:SM_Url_Startlive param:param datas:@[self.imageData] completion:^(NSURLSessionDataTask * _Nullable task, id  _Nullable result, NSError * _Nullable error) {
        if (!error) {
            if ([[result objectForKey:@"code"] integerValue] == 200) {
                NSDictionary *data = [result objectForKey:@"data"];
                if ([[data objectForKey:@"status"] boolValue] == YES) {
                    [ZBLiveChannel sharedInstance].channelId = [data objectForKey:@"channel_id"];
                    [ZBLiveChannel sharedInstance].channelPassword = [data objectForKey:@"channel_pwd"];
                    [weakSelf requestPolvLogin];
                }else{
                    [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                    [weakSelf.view makeToast:@"您的账号已被禁用"];
                }
            }else if ([[result objectForKey:@"code"] integerValue] == 201){
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                [[SMUserManager shareManager] login:weakSelf callBack:nil cancelBlock:nil];
                [weakSelf performBlock:^{
                    [GETWINDOW makeToast:@"Token已失效,请重新登录!"];
                } afterDelay:.8];
            }
            else{
                [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                [weakSelf.view makeToast:[result objectForKey:@"msg"]];
            }
        }else{
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            [weakSelf.view makeToast:TIP_LOAD_FAILED];
        }
    }];
}

- (void)requestPolvLogin
{
    WS(weakSelf)
    [[ZBLiveChannel sharedInstance] loginChannel:^(BOOL isSuccess, NSString *errorMsg) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (isSuccess) {
            ZBLiveViewController *controller = [[ZBLiveViewController alloc] init];
            controller.supportedInterfaceOrientation = weakSelf.horizontalBtn.selected ? UIInterfaceOrientationPortrait : UIInterfaceOrientationLandscapeLeft;
            controller.videoQuality = 4;
            ZBAppDelegate *delegate = (ZBAppDelegate *)[UIApplication sharedApplication].delegate;
            delegate.allowRotate = YES;
            [weakSelf presentViewController:controller animated:YES completion:nil];
        }else{
            [weakSelf.view makeToast:errorMsg];
        }
    }];
}

#pragma mark DELEGATE-TABLEVIEW
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.cells.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cells[indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.cells[indexPath.row].height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

#pragma mark Delegate-Picker
- (void)pickerDidSelectClass:(ZBLiveClass *)liveClass
{
    self.liveClass = liveClass;
    [self.tagBtn setTitle:STR_TO_STR(@"#", liveClass.cat_name) forState:UIControlStateNormal];
}

#pragma mark Delegate-ActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = YES;
    picker.delegate = self;
    if (buttonIndex == 0) {
        [SMHelper checkCameraAuthority:^(BOOL isPass) {
            if (isPass) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:picker animated:YES completion:nil];
            }
        }];
    }else if (buttonIndex == 1){
        [SMHelper checkPhotoAuthority:^(BOOL isPass) {
            if (isPass) {
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:picker animated:YES completion:nil];
            }
        }];
    }
}

#pragma mark Delegate-ImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [UIApplication sharedApplication].statusBarHidden = NO;
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqual:@"public.image"]) {
        UIImage *originImage = [info objectForKey:UIImagePickerControllerEditedImage];
        self.liveImageView.image = originImage;
        [self.picBtn setTitle:@"" forState:UIControlStateNormal];
        NSData *data = UIImageJPEGRepresentation(originImage, 0.5);
        self.imageData = data;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark Delegate-TextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return NO;
}

@end
